var Views = { };
var users;
var UsersView;
var UserView;
var User = Backbone.Model.extend({


        defaults : {


        address:"Sevastopol",
        phone:"+380500000000",

        status:0



},


    url:function() {
        return 'admin/create'
    }


});

var creationModel =  {
    header: "",
    button: "",
    message: ""
}
var header = [
    "Warning",
    "Error"
];
var userErrors = [
    "Please enter Login Name!",                           //0
    "Too short Login Name!",
    "Too long Login Name!",
    "Login Name cannot contain spaces!",
    "Login Name must starting with a letter!",
    "Please enter First Name!",                           //5
    "Too short First Name!",
    "Too long First Name!",
    "First Name must starting with a letter!",
    "Please enter Last Name!",                            //9
    "Too short Last Name!",
    "Too long Last Name!",
    "Last Name must starting with a letter!",
    "Please enter Password!",                             //13
    "Too short Password!",
    "Too long Password!",
    "Password cannot contain spaces!",
    "The value provided for the Password does not meet required complexity.",
    "Confirm Password is not equal to Password",              //18
    "Incorrect format of Email Address"                       //19

];
var messages = [
    "Are you sure you want to log out from the application?",
    "The user will be deleted from the list of users. Are you sure you want to proceed?",
    "Are you sure you want to cancel operation? All data will be lost.",
    "The order will be deleted from the list of orders. Are you sure you want to proceed?",
    "Are you sure you want to delete this item?",
    "This user was already deleted from the grid by another administrator. Please refresh the page to ensure.",
    "Please select items and add them to the order.",
    "Order Number already exists in the system. Please re-type it or just leave it blank.",
    "Delivery date is incorrect. Please re-type it to be at least 3 days after date of ordering.",
    "Start Date for Maestro card is incorrect. Please re-type it again.",
    "Issue number for Maestro card is incorrect. Please re-type it again.",
    "Credit card number is incorrect. Please re-type it again.",
    "CVV2 code is incorrect. Please re-type it again.",
    "Unfortunately you are not able to pay buy this credit card since expire date is too fast.",
    "Expire date is incorrect. Please re-type it again.",
    "Please re-assign the order to appropriate merchandiser"

];

var totalCount=0;
var totalPages;
var index = 1;
var paging = 10;
var search=false;
var SearchUserList = Backbone.Collection.extend({
    baseUrl: 'admin/users/find',
    initialize: function() {
        _.bindAll(this, 'url');
        this.field=$('#filter').val();
        this.value=$('#criteria').val();
        this.match=$('#method').val();
        this.index = index;
        this.size = paging;
    },
    url: function() {
        return this.baseUrl + '?' + $.param({
            field: this.field,
            value: this.value,
            match: this.match,
            index: this.index,
            size: this.size
        });
    }
});
var UserList = Backbone.Collection.extend({
    baseUrl: 'admin/users',
    initialize: function() {
        _.bindAll(this, 'url');
        this.index = index;
        this.size = paging;

    },
    url: function() {
        return this.baseUrl + '?' + $.param({
            index: this.index,
            size: this.size
        });
    }
});

$(function () {
    updatePaging();
    Backbone.emulateJSON = false;
    users = new UserList();
    var Controller = Backbone.Router.extend({
       routes: {
           "": "start",
           "create": "create",
           "edit": "edit",
           "duplicate": "duplicate"
       },

        start: function() {
          closeModal();
          closeUserEditor();
        },

        create: function() {
            closeUserEditor();
           // showUserEditor("create");
            if(Views.userEditor!=null) {
                creationModel = {
                    header: "Create New",
                    button: "Create",
                    message: "creating new"
                };
            Views.userEditor.render(creationModel);
            }
        },
        edit: function() {
            closeUserEditor();
           // showUserEditor("edit");
            if(Views.userEditor!=null) {
                creationModel = {
                    header: "Edit",
                    button: "Edit",
                    message: "editing existing"
                };
                Views.userEditor.render(creationModel);
            }
        },
        duplicate: function() {
            closeUserEditor();
           // showUserEditor("duplicate");
            if(Views.userEditor!=null) {
                creationModel = {
                    header: "Duplicate",
                    button: "Duplicate",
                    message: "duplicating"
                };
                Views.userEditor.render(creationModel);
            }
        }


    });
    var controller = new Controller();
    Backbone.history.start();

    var Start = Backbone.View.extend({
        el: $(".content"),
        events: {
            "click a#create": "create",
            "click a#show-paging": "paging",
            "click a.edit": "edit",
            "click a.duplicate": "duplicate",
            "click a.remove": "remove",
            "click #forward": "forward",
            "click #backward": "backward",
            "click #first": "first",
            "click #last": "last",
            "click #search-btn": "search"
        },
        create: function(e) {
            e.preventDefault();

            controller.navigate("create", true);
        },
        paging: function(e) {
            e.preventDefault();

                if (paging == 10) {
                    $("#show-paging span").html(paging);
                    paging = 25;
                } else {
                    $("#show-paging span").html(paging);
                    paging = 10;
                }
            index=1;
            buttonClick();
        },

        edit: function(e) {
            e.preventDefault();
            controller.navigate("edit", true);
        },

        duplicate: function(e) {
            e.preventDefault();
            controller.navigate("duplicate", true);
        },

        remove: function(e) {
            e.preventDefault();
            showModal(0,1);
            $('.modal-footer .btn-primary').one('click', function(event) {


                event.preventDefault();
                $.ajax({
                        type: "GET",
                        url: "admin/delete?id="+ $(e.currentTarget).attr("attr"),
                        async: false,
                        success:function() {
                            toastr.success("User was successfully deleted!");
                            buttonClick();


                        }
                    });
            });
        },

        forward: function(e) {
            e.preventDefault();
            index++;
            buttonClick();
        },
        backward: function(e) {
            e.preventDefault();
            index--;
            buttonClick();
        },
        first: function(e) {
            e.preventDefault();
            index=1;
            buttonClick();

        },
        last: function(e) {
            e.preventDefault();
            index=totalPages;
            buttonClick();
        },
        search: function(e) {
            e.preventDefault();

            if($('#criteria').val()==="") {
            search=false;
            } else {

                search=true;
            }
            index=1;
            buttonClick();
        }


    });

    var start = new Start();

    UserView = Backbone.View.extend({
        tagName: 'tr',
        template: _.template($("#row-user").html()),
        initialize: function(){
            _.bind(this.render, this);
        },
        render: function() {
            var element = this.template(this.model.toJSON());
            console.log(this.model.toJSON());
            $(this.el).html(element);
            return this;
        }


    });

    var UserEditor = Backbone.View.extend({
      el: $("#template"),
        template: _.template($("#create-template").html()),
      events: {
          "click .btn#cancel": "cancel",
          "click .btn#refresh": "refresh",
          "click .btn-primary#create-btn": "create"
      },
       cancel: function(e) {
           e.preventDefault();

           controller.navigate("", true);
       },
        refresh: function(e) {
            e.preventDefault();
        },
        create: function(e) {
            e.preventDefault();

            if(validate()) {

               var user = new User({
                    firstName:$('#firstname').val(),
                    lastName:$('#lastname').val(),
                    login:$('#name').val(),
                    password:$('#password').val(),
                    mail:$('#email').val(),
                    region:$('#region').val(),
                    role: {
                    roleId: $("input:radio[name ='role']:checked").val()
                    }
                    });
               console.log(user);
               user.save();
               toastr.success("User was successfully added!") ;

               buttonClick();
               controller.navigate("", true);

            }
        },
        render: function(model) {

            $(this.el).html(this.template(model));
        }


    });

    UsersView = Backbone.View.extend({
        el : $('#userListFrame'),

        initialize : function() {
            _.bindAll(this, 'addOne', 'addAll', 'render');
            users.bind('reset', this.addAll);
            users.bind('add', this.addOne);
            users.fetch();


        },
        addOne : function(user) {
            var view = new UserView({
                model : user
            });
            this.$('#table-users').append(view.render().el);
        },
        addAll : function() {

            users.each(this.addOne);
        }
    });

    Views = {
        userEditor: new UserEditor(),
        usersView: new UsersView()
    };

    // handlers for elements which are not in .content

    $("#button-exit").click(function (e) {
        e.preventDefault();
        showModal(0, 0);
        $('.modal-footer .btn-primary').one('click', function(event) {
            event.preventDefault();
            location.href="j_spring_security_logout";


        });
    });
    $(".modal-footer .btn").click(function (e) {
        e.preventDefault();
        closeModal();
    });


    /*
    $(".btn#create").click(function (e) {
        e.preventDefault();
        showUserEditor("create");
    });

    $("a.edit").click(function (e) {
        e.preventDefault();
        showUserEditor("edit");
    });

    $("a.duplicate").click(function (e) {
        e.preventDefault();
        showUserEditor("duplicate");
    });

    $(".container#create-user .btn#cancel").click(function (e) {
        e.preventDefault();
        closeUserEditor();
    });

    $(".container#create-user .btn#refresh").click(function (e) {
        e.preventDefault();
        closeUserEditor();
    });

    $(".edit").click(function (e) {
        e.preventDefault();
    });

    $(".remove").click(function (e) {
        e.preventDefault();
        showModal(0, 1);
    });

    $(".duplicate").click(function (e) {
        e.preventDefault();

    });
    */


});

function buttonClick() {
    if(search) {

        users = new SearchUserList();
    } else {
    users = new UserList();
    }
    userView = new UserView();

    updatePaging();
    Views.usersView = new UsersView();

    setTimeout(scrollDown, 100);
}
function updatePaging() {

    $.ajax({
            type: "GET",
            url: "admin/getCount",
            async: false,
            success:function(count) {

                totalCount = count;
                console.log(totalCount);
            }
        }
    ).responseText

    totalPages = Math.ceil(totalCount/paging);
    console.log(totalPages,totalCount, paging);
    $("#backward").attr("disabled", false);
    $("#forward").attr("disabled", false);
    $("#first").attr("disabled", false);
    $("#last").attr("disabled", false);
    if(index===1) {
        $("#backward").attr("disabled" ,true);
        $("#first").attr("disabled", true);
    }
    if(index===totalPages) {
        $("#forward").attr("disabled", true);
        $("#last").attr("disabled", true);
    }
    if(totalPages===1) {
        $("#first").attr("disabled" ,true);
        $("#last").attr("disabled" ,true);
    }

    $("#pageIndex").html(index);
    $("#totalPages").html(totalPages);
    $("#userListFrame #table-users tbody").html("");


}
function scrollDown() {
    $('html, body').animate({scrollTop: $("#foot").offset().top}, 1);
}

//modals, errors, warnings

function closeModal() {
    $("#modal").fadeOut();
}
function showModal(head, message, id) {
    if (head == 0) {
        $(".modal-footer .btn-primary").html("Yes");
        $(".modal-footer .btn#no").removeClass("hide");
    } else {
        $(".modal-footer .btn-primary").html("Ok");
        $(".modal-footer .btn#no").addClass("hide");

    }
    $(".modal-header h4").html(header[head]);
    $(".modal-body p").html(messages[message]);
    $("#modal").fadeIn();


}
function closeUserEditor() {

    $(".container#create-user").fadeOut();

}
/*function showUserEditor(action) {
 $(".container#create-user").fadeIn();
 switch (action) {
 case "create":
 $(".container#create-user legend span").html("Create New");
 $(".container#create-user div > span").html("creating new");
 $(".container#create-user .btn-primary").html("Create");
 break;
 case "edit":
 $(".container#create-user legend span").html("Edit");
 $(".container#create-user div > span").html("editing");
 $(".container#create-user .btn-primary").html("Edit");
 break;
 case "duplicate":
 $(".container#create-user legend span").html("Duplicate");
 $(".container#create-user div > span").html("duplicating");
 $(".container#create-user .btn-primary").html("Duplicate");
 break;
 }
 }
 */

//instruments for validating user's fields

function validate() {

    var array =[
        {id: "#name", field:"login"},
        {id: "#firstname",  field:"first"},
        {id: "#lastname",  field:"last"},
        {id: "#password",  field:"password"},
        {id: "#email",  field:"email"}

    ];
    var result ;
    var i=0;
    for(var rule in array) {
        result=validateString($(".container#create-user "+ array[rule].id).val(), array[rule].field);
        if(result != undefined) break;
    }


    if(result!=undefined)  {
        toastr.error(userErrors[result]);
        return false;
    } else if($(".container#create-user #password").val()!=$(".container#create-user #confirm-password").val())  {
        toastr.error(userErrors[18]);
        return false;
    } else {
        return true;
    }
};
function validateString(string, type) {
    switch (type) {
        case "login":
            return validateLogin(string);
            break;
        case "password":
            return validatePassword(string);
            break;
        case "first":
            var result = validateSimpleFields(string);
            if (result == undefined) {
                return ;
            }
            return result;
            break;
        case "last":
            var result = validateSimpleFields(string);
            if (result == undefined) {
                return ;
            }
            return result + 4;
            break;
        case "email":
            return validateEmail(string);
            break;
        default:
            return ;
    }
}
function validateLogin(string) {
    if (!string.trim()) {
        return 0;
    }
    if (string.length < 4) {
        return 1;
    }
    if (string.length > 20) {
        return 2;
    }
    var regex = /.*[\s]+.*/
    if (regex.test(string)) {
        return 3;
    }
    var regex = /[a-zA-Z]+/
    var firstLetter = string.charAt(0);
    if (!regex.test(firstLetter)) {
        return 4;
    }
    return ;
}
function validateSimpleFields(string) {
    if (!string.trim()) {
        return 5;
    }
    if (string.length < 3) {
        return 6;
    }
    if (string.length > 50) {
        return 7;
    }

    var regex = /[a-zA-Z]+/
    var firstLetter = string.charAt(0);
    if (!regex.test(firstLetter)) {
        return 8;
    }
    return ;
}
function validatePassword(string) {
    if (!string.trim()) {
        return 13;
    }
    if (string.length < 4) {
        return 14;
    }
    if (string.length > 10) {
        return 15;
    }
    var regex = /[A-Z]+/;
    if (!regex.test(string)) {
        return 17;
    }
    regex = /[a-z]+/;
    if (!regex.test(string)) {
        return 17;
    }
    regex = /[0-9]+/;
    if (!regex.test(string)) {
        return 17;
    }
    regex = /[!@#$%^&*()_+|~\-=\\\/'{}\[\]:";<>?,.]+/;
    if (!regex.test(string)) {

        return 27;
    }
    return ;
}
function validateEmail(string) {
    if (!string.trim()) {
        return 19;
    }
    var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (regex.test(string)) {
        return;
    }
    return 19;
}


